package control.networking;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;


/**
 * The ChatServer is almost like a cell phone tower, as it simply redirects messages
 * from one client and broadcasts them to all connected others.
 * @author Kevin Luikens
 *
 */
public class ChatServer extends Thread {
	
	private static final int port = 4000;
	private ConnectedChatters chatterList; // who's connected to the chatserver
	
	private ServerSocket 	serverSock;	// connection for the client, on the server
	private Socket 			clientSock;	// connection to the client
	
	
	/**
	 * Initializes a new ChatServer and waits for chatters to connect.
	 */
	public ChatServer() {
		System.out.println("ChatServer: created");
		chatterList = new ConnectedChatters();
		
		try {
			serverSock = new ServerSocket(port);
			System.out.println(serverSock);
		} catch ( Exception e ) {
			e.printStackTrace();	}
	}
	
	
	/**
	 * Broadcasts the message it received from a client and broadcasts it to
	 * everyone.
	 * @param message
	 */
	public void broadcast( String message ) {
		System.out.println("ChatServer: message -- " + message);
		chatterList.broadcast( message );
	}
	

	/**
	 * This is where the ChatServer waits for the connections
	 * and handles them accordingly (add to list of chatters and
	 * start the thread).
	 */
	public void run() {
		while(true) {
			System.out.println("Waiting for a chatter... ");
			try {
				clientSock = serverSock.accept();
				System.out.println(clientSock);
			} catch (IOException e) {
				e.printStackTrace();	}
			
			ChatServerHandler handler = new ChatServerHandler( clientSock, this );
			chatterList.addChatter( handler );
			new Thread( handler ).start();
		}
	}
	
}